package com.chhh.cranelease.controller;

import com.chhh.cranelease.entity.User;
import com.chhh.cranelease.model.ResponseCode;
import com.chhh.cranelease.model.UserWithRole;
import com.chhh.cranelease.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RequestMapping("user/")
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    private ResponseCode responseCode = new ResponseCode();

    @RequestMapping("login")
    public ResponseCode login(User user, HttpSession session){
        UserWithRole loginUser = userService.selectByLoginAcct(user);
        if (loginUser != null){
           session.setAttribute("user",loginUser);
           responseCode.setErrorCode(0);
           responseCode.setObject(loginUser);
           responseCode.setStatus("登录成功");
           return responseCode;
       }else {
           responseCode.setErrorCode(-1);
           responseCode.setStatus("账号或者密码错误");
           return responseCode;
       }
    }
    @RequestMapping("registered")
    public ResponseCode registered(User user){
        boolean userExist = userService.selecLoginAcct(user.getLoginAcct());
        System.out.println(userExist);
        System.out.println(user.getLoginAcct());
        if (userExist){
            responseCode.setErrorCode(-1);
            responseCode.setStatus("用户名已经存在");
            return responseCode;
        }else {
            userService.insertUser(user);
            responseCode.setErrorCode(0);
            responseCode.setStatus("注册成功");
            return responseCode;
        }
    }
    @RequestMapping("getUserInfo")
    public ResponseCode getUserInfo(HttpSession session){
        UserWithRole userWithRole = (UserWithRole) session.getAttribute("user");
        System.out.println(userWithRole.toString());
        responseCode.setObject(userWithRole);
        return responseCode;
    }
    @RequestMapping("updateInfo")
    public ResponseCode updateInfo(User user){
       if (userService.updateInfo(user) != null){
           responseCode.setErrorCode(1);
       }else {
           responseCode.setErrorCode(0);
       }
       return responseCode;
    }
}
